<?php
declare(strict_types=1);

namespace LiLei\Configs;

class MyConfig
{
    public static $dirname = "";

    /**
     * 获取配置 database.host.x.x1.x2，database 是文件名
     *
     * @param string $option database.host
     * @param null   $default  默认值
     * @param string $dirname  目录
     * @return mixed|string
     */
    public static function getConfig(string $option, $default = null, string $dirname = '')
    {
        $options = self::getExplodeOptions($option);
        if (empty($options)) return $default;

        // 设置目录
        if (strlen($dirname) > 0) self::setDirname($dirname);

        // 获取配置文件的路径
        $configFile = self::getConfigFilePath($options[0]);
        if (1 > strlen($configFile)) return $default;

        // 加载配置文件内容
        $array        = require $configFile;
        $config_value = "";
        foreach($options as $key => $value){
            if ($key === 0) continue;
            if (empty($array[$value]) === false) $config_value = $array[$value];
        }

        return empty($config_value) ? $array : $config_value;
    }// getConfig() end

    /**
     * 分割成索引数组
     *
     * @param string $options
     * @return false|string|string[]
     */
    public static function getExplodeOptions(string $options = "")
    {
        $explode = explode('.', $options);
        if (empty($explode[0])) return $options;

        return $explode;
    }// getExplodeOptions() end

    /**
     * @param string $filename
     * @return string
     */
    public static function getConfigFilePath(string $filename)
    {
        $filename = self::getDirname() .'/'. $filename . ".php";
        if (file_exists($filename)) return $filename;

        return "";
    }// getConfigFilePath() end

    /**
     * 设置日志目录
     * 目录在 project_root/config 下，自己设置，例："app/config"
     *
     * @param string $dirname "monolog"
     * @return $this
     */
    public static function setDirname(string $dirname = "config")
    {
        $search = "/vendor/lilei/my-config/src";
        // project_root/vendor/lilei/my-mono-log/src/MyMonoLog.php
        $dir    = dirname(__FILE__);
        $dir    = str_replace("\\", "/", $dir);
        $dir    = str_replace($search, "", $dir);
        //var_dump($dir);

        self::$dirname = $dir .'/'. $dirname;
    }// setDirname() end

    /**
     * 日志目录
     *
     * @return string
     */
    public static function getDirname()
    {
        // 如果 dirname 是未设置，则使用初始目录
        if (1 > strlen(self::$dirname)) self::setDirname();

        return self::$dirname;
    }// getDirname() end
}